<?php
/**
 * Special price list admin filter
 *
 * @author Lukas Normantas
 */
class Catalog_Model_ProductSearchFilter
{
    public function setData($data)
    {
        $form = $this->getForm();
        if ($form->isValid( $data )){
            $namespace = new Zend_Session_Namespace('Catalog_Model_ProductSearchFilter');
            $namespace->data = $form->getValues();
            return true;
        }
    }

    public function getData()
    {
        $namespace = new Zend_Session_Namespace('Catalog_Model_ProductSearchFilter');
        return $namespace->data ? $namespace->data : $this->getDefaultData();
    }

    public function setSort($field)
    {
        $current_sort = $this->getSort();
        if ($current_sort == $field . ' ASC') {
            $sort = $field . ' DESC';
        } else {
            $sort = $field . ' ASC';
        }
        $namespace = new Zend_Session_Namespace('Catalog_Model_ProductSearchFilter');
        $namespace->sort = $sort;
    }

    public function getSort()
    {
        $namespace = new Zend_Session_Namespace('Catalog_Model_ProductSearchFilter');
        return $namespace->sort ? $namespace->sort : $this->getDefaultSort();
    }

    ////////////////////////////////////////////////////////////////////////////

    public function filterQuery(Doctrine_Query $query)
    {
        $data = $this->getData();
        if ($data['phrase']){
            $query->addWhere( 'p.title LIKE ?' ,  '%'.$data['phrase'].'%' );
            $query->orderBy($this->getSort() );
        } else {
            $query->addWhere( '1 = 2' );
        }
        return $query;
    }

    protected $_form = null;

    public function getForm()
    {
        if ($this->_form == null){
            $this->_form = new Catalog_Form_QuickSearch();
            $this->_form->setDefaults( $this->getData() );
        }
        return $this->_form;
    }

    static public function getDefaultSort()
    {
        return 'p.created_at';
    }

    static public function getDefaultData()
    {
        return array( 'phrase' => '');
    }
    
    ////////////////////////////////////////////////////////////////////////////
    /*
     * Fetches paginator from active products with active specials of $this category
     */
    public function getFoundProductPaginator($current_page)
    {
        $q = Doctrine_Query::create()
           ->select('c.*, p.*, s.*')
           ->from( 'Catalog_Model_Product p' )
           ->leftJoin( 'p.Category c' )
           ->leftJoin( 'p.Specials s ON s.product_id = p.id '
                       .'AND s.start_at <= CURRENT_DATE AND s.end_at>=CURRENT_DATE')
           ->orderBy('p.created_at DESC' );
        $this->filterQuery($q);
        $results_per_page = 20;
        $doctrinePager = new Doctrine_Pager($q, $current_page, $results_per_page);
        $zendPaginator = Areal_Paginator::build($doctrinePager);
        return $zendPaginator;
    }
}